package org.finesys.chat.core.base.document.parser;

import org.finesys.chat.core.base.document.Document;
import org.finesys.chat.core.base.document.exception.BlankDocumentException;
import org.finesys.common.core.util.Utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * 文本解析
 */
public class TextDocumentParser implements DocumentParser {

    private final Charset charset;

    public TextDocumentParser() {
        this(Charset.defaultCharset());
    }

    public TextDocumentParser(Charset charset) {
        this.charset = charset;
    }

    @Override
    public Document parse(InputStream inputStream) {
        try {
            //String text =IOUtils.toString(inputStream, charset.displayName());
            ByteArrayOutputStream result = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int length;
            while ((length = inputStream.read(bytes)) != -1) {
                result.write(bytes, 0, length);
            }
            String text = result.toString(charset.displayName());
            if (Utils.isNullOrBlank(text)) {
                throw new BlankDocumentException("文本内容为空");
            } else {
                return Document.from(text);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
